package com.aixin.project.servlet.admin;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;

import com.aixin.project.conf.Configure;
import com.aixin.project.data.CommonConstants;
import com.aixin.project.data.Course;
import com.aixin.project.data.Expert;
import com.aixin.project.handler.CourseHandler;
import com.aixin.project.handler.ExpertHandler;
import com.aixin.project.util.AxMemcached;
import com.aixin.project.util.DateUtil;
import com.aixin.project.util.RequestUtil;

public class CreatelessonServlet extends AdminServlet {
	Logger logger = Logger.getLogger(CreatelessonServlet.class);
	@Override
	protected Template execute(HttpServletRequest request,
			HttpServletResponse response, Context ctx) {
		String filePath = this.getServletContext().getRealPath("\\")+ "images\\course\\";

		String lessoname="" ;
		int lessonType=0 ;
		String description="" ;
		String startime="" ;		
		String endtime="";
		long expertid =0;
		double baseprice=0 ;
		double addprice =0;
		double pointprice =0;
		String serviceName="" ;
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				// Create a factory for disk-based file items
				DiskFileItemFactory factory = new DiskFileItemFactory();

				// Set factory constraints
				// factory.setSizeThreshold(4096); // 设置缓冲区大小，4kb
				// factory.setRepository(tempPathFile);// 设置缓冲区目录

				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);

				// Set overall request size constraint
				upload.setSizeMax(4194304); // 设置最大文件尺寸，4MB

				FileItem fw = null;
				String[] files = null;
				List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
				Iterator<FileItem> i = items.iterator();
				while (i.hasNext()) {
					FileItem fi = (FileItem) i.next();
					if (fi.isFormField()) {
						if ("lessoname".equals(fi.getFieldName())) {
							lessoname = fi.getString();
						} else if ("lessonType".equals(fi.getFieldName())) {
							lessonType = NumberUtils.toInt((fi.getString()), 2);
						}else if ("description".equals(fi.getFieldName())) {
							description = fi.getString();
						}  else if ("startime".equals(fi.getFieldName())) {
							startime = fi.getString();
						} else if ("endtime".equals(fi.getFieldName())) {
							endtime = fi.getString();
						} else if ("expert".equals(fi.getFieldName())) {
							expertid = NumberUtils.toInt((fi.getString()), 1);
						} else if ("baseprice".equals(fi.getFieldName())) {
							baseprice = NumberUtils.toDouble(fi.getString(), 0);
						} else if ("addprice".equals(fi.getFieldName())) {
							addprice = NumberUtils.toDouble(fi.getString(), 0);
						} else if ("pointprice".equals(fi.getFieldName())) {
							pointprice = NumberUtils.toDouble(fi.getString(), 0);
						} else if ("serviceName".equals(fi.getFieldName())) {
							serviceName = fi.getString();
						}
					} else {
						String filename = fi.getName();
						files = filename.split("\\.");
						fw = fi;

					}

				}

				Date stardate = DateUtil.strToDate(startime);
				Date enddate = DateUtil.strToDate(endtime);

				Course c = new Course();
				c.setTitle(lessoname);
				c.setDescription(description);
				c.setBaseprice(baseprice);
				c.setAddprice(addprice);
				c.setPointprice(pointprice);
				c.setService(serviceName);
				c.setCoursetype(lessonType);
				c.setExpertid(expertid);

				c.setStarttime(stardate);
				c.setEndtime(enddate);

				int cid = CourseHandler.create(c);
				if (cid != -1) {
					ctx.put("createInfo", "创建课程成功，你可以继续添加课程!");
					//AxMemcached.delete(CommonConstants.MKEY_COURSE_LIST);
					if (fw != null) {
						fw.write(new File(filePath + "c_" + cid + "."+ files[1]));
					}
				} else {
					ctx.put("createInfo", "创建课程失败..请检查填写信息是否正确或与管理员联系!");

				}

			} catch (Exception e) {
				logger.error("create course error : "+e.getMessage());
			}
		} else {
			
			List<Expert> expertList = ExpertHandler.hallexpertList();
			String services[];
			String servername = (Configure.COURSE_SERVICE);
			if (servername.contains("|")) {
				services = servername.split("\\|");
			} else {
				services = new String[1];
				services[0] = servername;
			}
			ctx.put("service", services);
			ctx.put("experts", expertList);
		}

		return getTemplate("bg/creatlesson.vm");
	}
}
